package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.RequestPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;


@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Permission> selectAll() {
        List<Permission> list = permissionMapper.selectAll();
        return list;
    }

    @Override
    public void deleteByPerId(Long perId) {
        permissionMapper.deleteByPrimaryKey(perId);
    }

    @Override
    public PageInfo<Permission> selectByQO(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> list = permissionMapper.selectAll();
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //注入spring容器
    @Autowired
    private ApplicationContext ctx;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void  reload() {
        //删除角色和权限的关系   //全部删除 重新加载时会重新分配关系
        roleMapper.delete();
        //删除所有的权限
        permissionMapper.deleteAll();

        //获取所有的Controller
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beansWithAnnotation.values();
        //遍历所有的controller 获取controller方法对象
        for(Object controller:controllers){
            Method[] methods = controller.getClass().getSuperclass().getDeclaredMethods();
            //遍历方法对象
            for (Method method:methods){
                //判断方法上是否有注解
                if(method.isAnnotationPresent(RequiresPermissions.class)){
                    RequiresPermissions requestPermission = method.getAnnotation(RequiresPermissions.class);
                    String[] Strings = requestPermission.value();
                    String name = Strings[0];
                    String expression = Strings[1];

                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setExpression(expression);
                    //把权限信息保存到数据中
                    permissionMapper.insert(permission);
                }
            }
        }

    }
}
